<script setup lang="ts">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { reactive, ref } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'
import { ElMessage, ElMessageBox, ElDivider } from 'element-plus'
import { useI18n } from '@/hooks/web/useI18n'
import { Log } from '@/utils/logError'
import { resetUserPasswordApi } from '@/api/personal-center'
import { useUserStoreWithOut } from '@/store/modules/user'

const { t } = useI18n()

const { required } = useValidator()

const formSchema = reactive<FormSchema[]>([
  {
    field: 'password',
    label: t('personalCenter.oldPassword'),
    component: 'InputPassword',
    componentProps: {
      placeholder: t('personalCenter.oldPasswordPlaceholder')
    },
    colProps: {
      span: 24
    }
  },
  {
    field: 'newPassword',
    label: t('personalCenter.newPassword'),
    component: 'InputPassword',
    componentProps: {
      placeholder: t('personalCenter.newPasswordPlaceholder'),
      strength: true
    },
    colProps: {
      span: 24
    }
  },
  {
    field: 'newPassword2',
    label: t('personalCenter.confirmPassword'),
    component: 'InputPassword',
    componentProps: {
      placeholder: t('personalCenter.confirmPlaceholder'),
      strength: true
    },
    colProps: {
      span: 24
    }
  }
])

const rules = reactive({
  password: [required()],
  newPassword: [
    required(),
    {
      asyncValidator: async (_, val, callback) => {
        const formData = await getFormData()
        const { newPassword2 } = formData
        if (val !== newPassword2) {
          callback(new Error(t('personalCenter.passwordNotMath')))
        } else {
          callback()
        }
      }
    }
  ],
  newPassword2: [
    required(),
    {
      asyncValidator: async (_, val, callback) => {
        const elForm = await getElFormExpose()
        const newPasswordRef = elForm?.fields.find((item) => item.prop === 'newPassword')
        newPasswordRef.validate().catch((err) => {})
        const formData = await getFormData()
        const { newPassword } = formData
        if (val !== newPassword) {
          callback(new Error(t('personalCenter.passwordNotMath')))
        } else {
          callback()
        }
      }
    }
  ]
})

const { formRegister, formMethods } = useForm()
const { getFormData, getElFormExpose } = formMethods

const saveLoading = ref(false)
const save = async () => {
  const elForm = await getElFormExpose()
  try {
    await elForm?.validate()
    await ElMessageBox.confirm(t('common.confirmSave'), t('common.notice'), {
      confirmButtonText: t('common.save'),
      cancelButtonText: t('common.cancel'),
      type: 'warning'
    })
    saveLoading.value = true
    const { password, newPassword } = await getFormData()
    // 这里可以调用修改密码的接口
    const { message } = await resetUserPasswordApi({
      old_password: password,
      new_password: newPassword
    })
    ElMessage.success(message)
    saveLoading.value = false
    const userStore = useUserStoreWithOut()
    userStore.logout()
  } catch (error) {
    Log.error('Modify Password', error)
  }
}
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="formSchema" />
  <ElDivider />
  <BaseButton type="primary" @click="save">{{ t('common.save') }}</BaseButton>
</template>
